<?php

namespace app\api\controller;

use app\admin\model\User as UserMdl;
use app\admin\model\Store;
use app\admin\model\Ticket;
use app\common\model\Specialofferrule;

use think\Db;
use think\Exception;

/**
 * 个人中心
 */
class User extends Base
{

    /**
     * 个人资料
     */
    public function userInfo(){
        $param = self::getHttpParam();

        if (empty($param->openId)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'openId 不能为空');
        }

        $where = [
            'openId' => $param->openId,
        ];

        $fields = '*';
        $item = UserMdl::where($where)->field($fields)->find();

        if (empty($item)) {
            return show(config('status.error_code'), self::NOT_DATA, '未查个人资料');
        }

        return show(config('status.success_code'), self::MSG_SUCCESS, $item);
    }

    /**
     * 保存个人资料
     */
    public function saveUser(){
        $param = self::getHttpParam();

        if (empty($param->userId)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->userName)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'userName 不能为空');
        }
        if (empty($param->imgUrl)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'imgUrl 不能为空');
        }
        if (empty($param->sex)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'sex 不能为空');
        }

        $id = $param->userId;
        $model = new UserMdl();

        Db::startTrans();
        $userInfo = $model->find($id);
        $userInfo->userName = $param->userName;
        $userInfo->imgUrl = $param->imgUrl;
        $userInfo->sex = $param->sex;
        if($param->birthday == '1970-01-01'){
            $userInfo->birthday = NULL;
        }else{
            $userInfo->birthday = $param->birthday;
        }
        $userInfo->phone = $param->phone;

        $result = $userInfo->allowField(true)->save();

        if ($result !== false) {
            Db::commit();
        } else {
            Db::rollback();
            return show(config('status.error_code'), self::MSG_ERROR, $model->getError());
        }

        return show(config('status.success_code'), self::MSG_SUCCESS, $userInfo);
    }

    /**
     * 优惠券
     *
     * @return \think\response\Json
     */
    public function myTickets()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        if (empty($param->userId)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->status) && $param->status != 0) {
            return show(config('status.error_code'), self::NOT_PARAM, 'status 不能为空');
        }
        if (!in_array($param->status, [0, 1, 2])) {
            return show(config('status.error_code'), self::NOT_PARAM, 'status 格式不正确');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $userId = $param->userId;
        $where = [
            'a.userId' => $userId,
            'a.status' => $param->status
        ];


        $join = [
            ['__TICKET__ t','t.id=a.ticketId']
        ];
        $model = db('Userreceivetic');
        $fields = 't.id,t.name,t.specialOfferId,t.beginTime,t.endTime,t.status as tstatus,a.id as receiveticId, a.userId, a.storeId, a.ticketId, a.receiveTicketTime, a.status as status';
        $result = model('Userreceivetic')->alias('a')->where($where)->join($join)->order('a.receiveTicketTime DESC')->field($fields)->limit($start, $length)->select();
        $total = model('Userreceivetic')->alias('a')->where($where)->join($join)->count();

        if (empty($result)) {
            return show(config('status.error_code'), self::NOT_DATA, '未查到优惠券');
        }

        foreach ($result as &$item){

            $Specialofferrule = Specialofferrule::get($item->specialOfferId);
            $item['specialOfferRule'] = $Specialofferrule;
            $storeInfo = Store::get($item['storeId']);
            $item['store'] = $storeInfo;

            // 优惠券领取数
            $item['countReceive'] = $model->where('id', $item['ticketId'])->count();
        }

        return showTotal(config('status.success_code'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 关注
     *
     * @return \think\response\Json
     */
    public function myFocus()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        if (empty($param->userId)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $userId = $param->userId;
        $where = [
            'userId' => $userId,
        ];

        $model = db('userfocus');
        $fields = 'userId, storeId, focusTime';
        $result = $model->where($where)->field($fields)->limit($start, $length)->select();
        $total = $model->where($where)->count();

        if (empty($result)) {
            return show(config('status.error_code'), self::NOT_DATA, '未查到关注');
        }

        foreach ($result as &$item) {
            $storeInfo = Store::field('name,imgUrl')->find($item['storeId']);
            //$item['storeInfo'] = $storeInfo;
            $item['storeName'] = $storeInfo['name'];
            $item['storeImg'] = $storeInfo['imgUrl'];
            $item['countFocus'] = $model->where('storeId', $item['storeId'])->count();
        }

        return showTotal(config('status.success_code'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 进店记录
     */
    public function myUserinstore(){
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        if (empty($param->userId)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->storeId)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'storeId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $userId = $param->userId;
        $where = [
            //'userId' => $userId,
            'a.storeId' => $param->storeId
        ];

        $model = db('userinstore');
        $fields = 'a.userId, a.storeId, a.inStoreStatus, a.inStoreCount, a.inStoreTime, u.userName, u.imgUrl';
        $result = $model->alias('a')->where($where)->join('user u', 'a.userId = u.id')->field($fields)->limit($start, $length)->order('a.inStoreTime DESC')->select();
        $total = $model->alias('a')->where($where)->join('user u', 'a.userId = u.id')->count();

        if (empty($result)) {
            return show(config('status.error_code'), self::NOT_DATA, '未查到进店');
        }

        return showTotal(config('status.success_code'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 被关注
     */
    public function myBeFocus(){
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        if (empty($param->storeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'storeId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'a.storeId' => $param->storeId
        ];

        $model = db('userfocus');
        $fields = 'a.userId, a.storeId, a.focusTime, u.userName, u.imgUrl';
        $result = $model->alias('a')->where($where)->join('user u', 'a.userId = u.id')->field($fields)->limit($start, $length)->order('a.focusTime DESC')->select();
        $total = $model->alias('a')->where($where)->join('user u', 'a.userId = u.id')->count();

        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到被关注');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

}